const Koa = require('koa')
const path = require('path')
const bodyParse = require('koa-bodyparser')
const static_ = require('./static-files')
const Cookies = require('cookies')

// 静态文件服务中间件
// 初始化路由
const initRouter = require('./controller')
// 注册nunjuck模版
const initTempalte = require('./templating')


const app = new Koa()
app.use(static_('/static/',path.join(__dirname,'./static')))
app.use(async (ctx, next) => {
  ctx.state.user = parseUser(ctx.cookies.get('name') || '');
  await next();
});
app.use(initTempalte('views', {noCache: true, watch: true}))
app.use(bodyParse())
app.use(initRouter())


app.listen('3000')

function parseUser(obj) {
  if (!obj) {
      return;
  }
  console.log('try parse: ' + obj);
  let s = '';
  if (typeof obj === 'string') {
      s = obj;
  } else if (obj.headers) {
      let cookies = new Cookies(obj, null);
      s = cookies.get('name');
  }
  if (s) {
      try {
          let user = JSON.parse(Buffer.from(s, 'base64').toString());
          console.log(`User: ${user.name}, ID: ${user.id}`);
          return user;
      } catch (e) {
          // ignore
      }
  }
}

